'use strict';

const Controller = require('egg').Controller;
const fs = require("mz/fs");
const path = require("path");
class CommonController extends Controller {
    // 上传
    async upload() {
        const ctx = this.ctx;
        const currentUser = ctx.authUser;
        console.log(currentUser, "curr")
        if (!ctx.request.files) {
            return ctx.apiFail("请先选择上传文件", "请先选择上传文件", 200);
        }
        // ctx.validate({
        //     file_id: {
        //         type: "int",
        //         required: true,
        //         defValue: 0,
        //         desc: "file_id"
        //     }
        // })

        const file = ctx.request.files[0];
        console.log(file, "file")
        // const name = 'egg-oss-demo/' + path.basename(file.filename);
        const name = "egg-oss-demo/" + ctx.genID(10) + path.extname(file.filename);
        let s = await (new Promise((resolve, reject) => {
            fs.stat(file.filepath, (err, stats) => {
                resolve((stats.size / 1024).toFixed(1))
            })
        }))
        console.log(s, "ss");
        if ((currentUser.total_size - currentUser.used_size) < s) {
            return ctx.apiFail("用户内存不足")
        }
        let result;
        try {
            result = await ctx.oss.put(name, file.filepath);
        } catch (err) {
            console.log(err);
        } finally {
            await fs.unlink(file.filepath);
        }
        console.log(result, "result")
        let ext = "";
        if (file.mimeType.includes("image")) {
            ext = "image";
        }else if (file.mimeType.includes("video")) {
            ext = "video";
        }else  if (file.mimeType.includes("audio")) {
            ext = "audio";
        }else{
            ext = "more";
            
        }

        if (result) {
            let addData = {
                name: file.filename,
                ext: ext,
                md: result.name,
                user_id: currentUser.id,
                size: parseInt(s),
                isdir: 0,
                url: result.url
            }
            let res = this.app.model.File.create(addData);

            currentUser.used_size = currentUser.used_size + parseInt(s)
            currentUser.save()
            return ctx.apiSuccess(res, "上传成功", 200);
        }

        ctx.apiFail("上传失败");
    }
}

module.exports = CommonController;